package main

import (
	"fmt"
	"io"
	"os"
	"bufio"
	"io/ioutil"
	"strconv"
)
func ReadFile1(FileName string){
	file,err:=os.Open(FileName)
	defer file.Close()
	if err!=nil{
		fmt.Println("open file fail! err:=",err)
		return
	}
	sliceTemp:=make([]byte,120)
	var sliceTotal []byte
	for{
		n,err:=file.Read(sliceTemp)
		if err==io.EOF{
			fmt.Println("文件读完")
			break;
		}
		if err!=nil{
			fmt.Println("读取文件失败")
			return
		}
		sliceTotal=append(sliceTotal,sliceTemp[:n]...)
	}
	fmt.Println(string(sliceTotal))
}
func ReadFile2(fileName string){
	file,err:=os.Open(fileName)
	file.Close()
	if err!=nil{
		fmt.Println("open file fail! err=",err)
		return
	}
	reader:=bufio.NewReader(file)
	var str string
	for{
		line,err:=reader.ReadString('\n')	
		if err==io.EOF{
			str+=line
			break
		}
		if err!=nil{
			fmt.Println("读取文件失败")
			return
		}
		str+=line
	}
	fmt.Println(str)
}

func ReadFile3(fileName string)error{
	// file,err:=os.Open(fileName)
	// if err!=nil{
	// 	fmt.Println("open file fail! err=",err)
	// 	return
	// }
	slice,err:=ioutil.ReadFile(fileName)
	if err!=nil{
		fmt.Println("读取文件失败")
		return err
	}
	fmt.Println(string(slice))
	return nil
}
func WriteFile1(fileName string){
	file,err:=os.OpenFile(fileName,os.O_CREATE|os.O_RDWR,0666)
	defer file.Close()
	if err!=nil{
		fmt.Println("OpenFile fail,err=",err)
		return
	}
	file.WriteString("hello world\n")
	str:="cquptyyy\n"
	file.Write([]byte(str))
}
func WriteFile2(fileName string){
	file,err:=os.OpenFile(fileName,os.O_RDWR|os.O_CREATE|os.O_APPEND,0666)
	defer file.Close()
	if err!=nil{
		fmt.Println("open file fail! err=",err)
		return
	}
	writer:=bufio.NewWriter(file)
	for i:=1;i<=10;i++{
		writer.WriteString("this a string - "+strconv.Itoa(i)+"\n")
	}
	writer.Flush()
}
func WriteFile3(fileName string){
	// file,err:=os.OpenFile(fileName,os.O_RDWR|os.O_CREATE|os.O_APPEND,0666)
	
	// if err!=nil{
	// 	fmt.Println("open file fail,err=",err)
	// 	return
	// }
	str:="my name is cquptyyy\n"
	ioutil.WriteFile(fileName,[]byte(str),0666)
}
func main(){
	//FileName:="./test.txt"
	//ReadFile1(FileName)
	//ReadFile2(FileName)
	// err:=ReadFile3(FileName)
	// if err!=nil{
	// 	fmt.Println("读取文件失败")
	// 	return
	// }
	fileName:="./test1.txt"
	//WriteFile1(fileName)
	//WriteFile2(fileName)
	WriteFile3(fileName)
}